package com.java.collection;

import java.util.Arrays;

class SimpleArrayList<E> {//ArrayList<E>
    /**通过数组存储元素*/
   private Object[] array;
   /**用来记录有效元素个数*/
   private int size;
   public SimpleArrayList(){
       this(16);
   }
   public SimpleArrayList(int cap){
       array=new Object[cap];
   }
   /**向数组的size位置添加元素*/
   public void add(E data){
       //1.容器是否满了,满了要扩容
       if(size==array.length)
           array= Arrays.copyOf(array,2*array.length);
       //2.存储元素
       array[size]=data;
       //3.有效元素个数加1
       size++;
   }
    /**向数组的index位置存储元素*/
    public void add(int index,E data){
      //1.判断index是否越界
        if(index<0||index>size)
            throw new IndexOutOfBoundsException();
      //2.判断容器是否已满
        if(size==array.length)
            array= Arrays.copyOf(array,2*array.length);
      //3.移动元素
        System.arraycopy(array,index,array,index+1,size-index);
      //4.存储元素
        array[index]=data;
      //5.有效元素个数加
        size++;
    }
    /**移除index位置的元素*/
    public E remove(int index){
        //1.判断index是否越界
        if(index<0||index>size)
            throw new IndexOutOfBoundsException();
        //2.获取index位置的元素
        Object data=array[index];
        //3.移动元素
        System.arraycopy(array,index+1,array,index,size-1-index);
        array[--size]=null;
        //4.返回移除的元素
        return (E)data;
    }

    public int size(){
       return size;
   }

    @Override
    public String toString() {
        StringBuilder sb=new StringBuilder();
        sb.append("[");
        for(int i=0;i<size;i++){
            sb.append(array[i]).append(",");
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        sb.append("]");
        return sb.toString();
    }
}

public class SimpleArrayListTests {
    public static void main(String[] args) {
        SimpleArrayList list=new SimpleArrayList();
        list.add("A");
        list.add("B");
        list.add("C");
        list.add(0,"D");
        list.remove(2);
        System.out.println(list);
    }
}
